﻿using Dapper;
using System;
using BCEntity.Trading.SaleGoods.SaleGoodsCategory;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.Trading.SaleGoods.SaleGoodsCategory
{
    /// <summary>
    /// 销售商品分类
    /// </summary>
    public class SaleGoodsCategoryData : ISaleGoodsCategoryData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM salegoodscategory";
        private const string QUERY = @"SELECT SaleGoodsCategoryId,CreateAdminId,CreateAdminName,CreateTime,UpdateTime,EditAdminId,EditAdminName,CategoryName,CategoryNamePinyin,CategoryIcon,Level,TreePath,ParentId,GoodsCount,SearchLevel,Enabled FROM salegoodscategory";
        public SaleGoodsCategoryData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        #region 检查销售商品分类是否存在
        public async Task<bool> Exists(long saleGoodsCategoryId)
        {
            string sql = string.Format(@"{0} WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 检查销售商品分类是否存在子级分类
        public async Task<bool> ChildrenExists(long saleGoodsCategoryId)
        {
            string sql = string.Format(@"{0} WHERE ParentId=?SaleGoodsCategoryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加销售商品分类
        public async Task<SaleGoodsCategoryEntity> Add(SaleGoodsCategoryEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("salegoodscategory", new string[] { "CreateAdminId", "CreateAdminName", "CategoryName", "CategoryNamePinyin", "CategoryIcon", "Level", "TreePath", "ParentId" });
            sql = string.Format("{0} {1} WHERE SaleGoodsCategoryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?CategoryNamePinyin", entity.CategoryNamePinyin?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryIcon", entity.CategoryIcon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?Level", entity.Level, DbType.Int32, size: 11);
            parameters.Add("?TreePath", entity.TreePath?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?ParentId", entity.ParentId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleGoodsCategoryEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改销售商品分类
        public async Task<SaleGoodsCategoryEntity> Update(SaleGoodsCategoryEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("salegoodscategory", new string[] { "EditAdminId", "EditAdminName", "CategoryName", "CategoryNamePinyin", "CategoryIcon", "Level", "TreePath", "ParentId", "GoodsCount", "SearchLevel" }, new string[] { "SaleGoodsCategoryId" });
            sql = string.Format("{0} {1} WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            parameters.Add("?CategoryNamePinyin", entity.CategoryNamePinyin?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CategoryIcon", entity.CategoryIcon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?Level", entity.Level, DbType.Int32, size: 11);
            parameters.Add("?TreePath", entity.TreePath?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?ParentId", entity.ParentId, DbType.Int64, size: 20);
            parameters.Add("?GoodsCount", entity.GoodsCount, DbType.Int32, size: 11);
            parameters.Add("?SearchLevel", entity.SearchLevel, DbType.Int32, size: 11);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleGoodsCategoryEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除销售商品分类
        public async Task<bool> Delete(long saleGoodsCategoryId)
        {
            string sql = @"DELETE FROM salegoodscategory WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取销售商品分类
        public async Task<SaleGoodsCategoryEntity> GetEntity(long saleGoodsCategoryId)
        {
            string sql = string.Format(@"{0} WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SaleGoodsCategoryEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售商品分类列表
        public async Task<IEnumerable<SaleGoodsCategoryEntity>> GetList()
        {
            string sql = string.Format(@"{0} WHERE Enabled=1 ORDER BY TreePath ASC", QUERY);
            return await this.databaseContext.Slave.QueryAsync<SaleGoodsCategoryEntity>(sql);
        }
        public async Task<IEnumerable<SaleGoodsCategoryEntity>> GetList(int size)
        {
            string sql = string.Format(@"{0} WHERE Enabled=1 ORDER BY TreePath ASC LIMIT {1}", QUERY, size);
            return await this.databaseContext.Slave.QueryAsync<SaleGoodsCategoryEntity>(sql);
        }
        #endregion

        #region 获取销售商品分类分页
        public async Task<(IEnumerable<SaleGoodsCategoryEntity>, int)> Query(long? saleGoodsCategoryId,bool? enabled, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (saleGoodsCategoryId.HasValue)
            {
                wheres.Add("FIND_IN_SET(?SaleGoodsCategoryId,TreePath)");
                parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId.Value, DbType.Int64);
            }
            if (enabled.HasValue)
            {
                wheres.Add("Enabled=?Enabled");
                parameters.Add("?Enabled", enabled.Value, DbType.Boolean);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM salegoodscategory {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<SaleGoodsCategoryEntity, int>(sql, parameters);
        }
        #endregion

        #region 启用销售商品分类
        public async Task<bool> Enabled(long saleGoodsCategoryId)
        {
            string sql = @"UPDATE salegoodscategory SET Enabled=1 WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 禁用销售商品分类
        public async Task<bool> Disabled(long saleGoodsCategoryId)
        {
            string sql = @"UPDATE salegoodscategory SET Enabled=0 WHERE SaleGoodsCategoryId=?SaleGoodsCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleGoodsCategoryId", saleGoodsCategoryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion
    }
}



